package com.uduemc.biso.node.web.component.operate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.uduemc.biso.core.extities.center.Site;
import com.uduemc.biso.core.extities.node.custom.LoginNode;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModel;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModelAction;
import com.uduemc.biso.node.core.operate.entities.OperateLog;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.SiteService;
import com.uduemc.biso.node.web.utils.JwtTokenUtils;

@Aspect
@Component
public class OperateLoggerLoginController extends OperateLoggerController {

	@Autowired
	private GlobalProperties globalProperties;

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.LoginController.login(..))", returning = "returnValue")
	public void login(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();
		String modelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String modelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.LOGIN);

		// 参数1
		String paramString = objectMapper.writeValueAsString(args[0]);

		JsonResult jsonResult = (JsonResult) returnValue;
		@SuppressWarnings("unchecked")
		Map<String, String> results = (HashMap<String, String>) jsonResult.getData();
		String authorizationToken = results.get("jsessionid");

		String sessionKey = JwtTokenUtils.getUsername(authorizationToken);
		if (!StringUtils.hasText(sessionKey)) {
			throw new RuntimeException("authorizationToken 未能通过 JwtTokenUtils 解析！");
		}

		String redisKey = globalProperties.getNodeRedisKey().makeNodeRedisKey(sessionKey);
		if (!StringUtils.hasText(redisKey)) {
			throw new RuntimeException("解析的 AuthorizationTokenSessionKey 未能获取到 redisKey ！");
		}

		RedisUtil redisUtil = SpringContextUtils.getBean("redisUtil", RedisUtil.class);
		LoginNode loginNode = (LoginNode) redisUtil.get(redisKey);
		Long currentSiteId = loginNode.getCurrentSiteId();
		if (loginNode == null || loginNode.getLoginUserId().longValue() < 1L) {
			throw new RuntimeException("通过 redisKey 未能获取到对应的缓存数据 ！redisKey: " + redisKey);
		}

		String name = loginNode.getCustomerUser().getName();
		if (StringUtils.isEmpty(name)) {
			name = loginNode.getCustomerUser().getUsername();
		}
		String content = "登录站点（" + name + "）";

		String returnValueString = objectMapper.writeValueAsString(returnValue);

		SiteService siteServiceImpl = SpringContextUtils.getBean("siteServiceImpl", SiteService.class);
		Site site = null;
		if (currentSiteId == null) {
			site = siteServiceImpl.getDefaultSite(loginNode.getHost().getId());
		} else {
			site = siteServiceImpl.getInfoById(currentSiteId);
		}
		OperateLog log = makeOperateLog(site.getHostId(), site.getId(), site.getLanguageId(), loginNode, modelName,
				modelAction, content, paramString, returnValueString, "", (short) 1);
		insertOperateLog(log);
	}
}
